<template>
  <ContentWrap class="mobile-container">
    <!--    顶部查询项-->
    <el-form :model="form" inline label-width="110px" class="mobile-form">
      <el-form-item :label="t('orderReturn.returnorder_no')">
        <el-input
          v-model="form.returnorder_no"
          clearable
          :placeholder="t('orderReturn.returnorder_no')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('orderReturn.customer_id')">
        <el-input v-model="form.customer_name" clearable disabled style="width: 250px" />
        <el-button class="m-l-20px" size="small" type="primary" @click="handleOpenCustomer"
          >{{ t('wholesalOrder.selectCustomers') }}
        </el-button>
      </el-form-item>
      <el-form-item :label="t('orderReturn.signatory')" prop="signatory">
        <el-select
          v-model="form.signatory"
          :filterable="true"
          :placeholder="t('orderReturn.signatory')"
          :clearable="false"
          style="width: 150px"
        >
          <el-option
            v-for="item in operatorList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('orderReturn.signing_date')">
        <el-date-picker
          v-model="form.date"
          type="daterange"
          format="YYYY/MM/DD"
          range-separator="-"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          @change="changeTime"
          :editable="false"
          unlink-panels
        />
      </el-form-item>

      <el-form-item :label="t('orderReturn.total_amount')" prop="total_amount">
        <div style="display: flex; flex-wrap: nowrap; align-items: center; width: 100%">
          <el-input-number
            v-model="form.min_total_amount"
            :min="1"
            :max="10000000"
            size="small"
            controls-position="right"
          />
          <span style="margin: 0 8px">~</span>
          <el-input-number
            v-model="form.max_total_amount"
            :min="1"
            :max="10000000"
            size="small"
            controls-position="right"
          />
        </div>
      </el-form-item>
      <el-form-item :label="t('orderReturn.paid_amount')" prop="paid_amount">
        <div style="display: flex; flex-wrap: nowrap; align-items: center; width: 100%">
          <el-input-number
            v-model="form.min_paid_amount"
            :min="1"
            :max="10000000"
            size="small"
            controls-position="right"
          />
          <span style="margin: 0 8px">~</span>
          <el-input-number
            v-model="form.max_paid_amount"
            :min="1"
            :max="10000000"
            size="small"
            controls-position="right"
          />
        </div>
      </el-form-item>
      <el-form-item :label="t('orderReturn.return_reason')" prop="return_reason">
        <el-select
          v-model="form.return_reason"
          :filterable="true"
          :placeholder="t('orderReturn.return_reason')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in reasonList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('orderReturn.returnorder_type')" prop="returnorder_type">
        <el-select
          v-model="form.returnorder_type"
          :filterable="true"
          :placeholder="t('orderReturn.returnorder_type')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in returnorderTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <div class="flex flex-items-center my-5">
      <el-button type="primary" @click="handleJump('add')">
        {{ t('system.marketChannel.add') }}
      </el-button>
    </div>

    <!-- 移动端卡片视图 -->
    <div v-if="isMobile" class="mobile-card">
      <el-card v-for="item in dataList" :key="item.id" class="return-order-card">
        <template #header>
          <div class="card-header">
            <el-link :underline="false" type="primary" @click="handleJump('detail', item)">
              {{ item.returnorder_no }}
            </el-link>
            <el-tag :type="getStatusTagType(item.status)" size="small">
              {{ useEnumeratePicker(statusList, item.status) }}
            </el-tag>
          </div>
        </template>

        <div class="card-content">
          <div class="info-row">
            <span class="label">{{ t('orderReturn.customer_id') }}:</span>
            <span class="value">{{ item.customer_name || '-' }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('orderReturn.returnorder_type') }}:</span>
            <span class="value">{{
              useEnumeratePicker(returnorderTypeList, item.returnorder_type)
            }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('orderReturn.return_reason') }}:</span>
            <span class="value">{{ useEnumeratePicker(reasonList, item.return_reason) }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('orderReturn.total_amount') }}:</span>
            <span class="value">{{ item.total_amount || '0.00' }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('orderReturn.paid_amount') }}:</span>
            <span class="value">{{ item.paid_amount || '0.00' }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('orderReturn.signatory') }}:</span>
            <span class="value">{{ useEnumeratePicker(operatorList, item.signatory) }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('orderReturn.signing_date') }}:</span>
            <span class="value">{{ item.signing_date || '-' }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('orderReturn.create_time') }}:</span>
            <span class="value">{{ item.create_time || '-' }}</span>
          </div>
        </div>

        <!-- 移动端操作按钮 -->
        <div class="card-actions">
          <el-button
            type="primary"
            size="small"
            @click="handleJump('edit', item)"
            v-if="item.status === 1"
            class="action-btn"
          >
            {{ t('system.marketChannel.edit') }}
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="examineHandle(item, 1)"
            v-if="item.status === 1"
            v-hasPermi="['OrderReturnManageAudit']"
            class="action-btn"
          >
            {{ t('purchase.examine_pass') }}
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="examineHandle(item, 2)"
            v-if="item.status === 1"
            class="action-btn"
          >
            {{ t('common.reject') }}
          </el-button>
          <el-button
            type="success"
            size="small"
            @click="handleJump('detail', item)"
            class="action-btn"
          >
            {{ t('action.detail') }}
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleCancel('single', item)"
            v-if="item.status === 1 && userStore.getUserInfo?.id == item.creator"
            class="action-btn"
          >
            {{ t('common.cancelExamine') }}
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 桌面端表格视图 -->
    <div v-else class="mobile-table">
      <Table
        showAction
        :data="dataList"
        :columns="tableColumns"
        highlight-current-row
        stripe
        border
        :loading="tableLoading"
        align="center"
        header-align="center"
        row-key="id"
        @selection-change="handleSelectionChange"
      />
    </div>

    <!--    分页-->
    <Pagination
      class="mobile-table"
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>

  <DialogCustomerChecked
    ref="DialogCustomerCheckedRef"
    @expose-multiple-data="getExposeCustomerData"
    class="mobile-dialog"
  />
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import {
  cancelDataApi,
  cancelSingleDataApi,
  getEnumApi,
  getListApi,
  examineDataApi
} from '@/api/orderReturn'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { useClipboard } from '@vueuse/core'
import DialogCustomerChecked from '@/views/OrderReturn/OrderReturnManage/components/DialogCustomerChecked/index.vue'
import { Table } from '@/components/Table'
import { useOrderReturnTableColumns } from './components/hooks/useTableColumns'
import { useAppStore } from '@/store/modules/app'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const { copy } = useClipboard()
const { t } = useI18n()
const { push } = useRouter()
const appStore = useAppStore()

// 移动端检测
const isMobile = computed(() => appStore.getMobile)

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const DialogCustomerCheckedRef = ref()

const paginationTotal = ref<number>(0)
const form = ref<Record<string, any>>({
  returnorder_no: '',
  customer_name: '',
  owner: '',
  date: '',
  min_total_amount: undefined,
  max_total_amount: undefined,
  min_paid_amount: undefined,
  max_paid_amount: undefined,
  return_reason: '',
  signing_start_date: '',
  signing_end_date: '',
  pageIndex: 1,
  pageSize: 20
})

const modelList = ref<Array<Record<string, any>>>([])
const operatorList = ref<Array<Record<string, any>>>([])
const reasonList = ref<Array<Record<string, any>>>([])
const returnorderTypeList = ref<Array<Record<string, any>>>([])
const orderTypeList = ref<Array<Record<string, any>>>([])
const statusList = ref<Array<Record<string, any>>>([])

// 获取状态标签类型
const getStatusTagType = (status: string | number) => {
  switch (status) {
    case 1:
      return 'warning' // 待审核
    case 2:
      return 'success' // 已审核
    case 3:
      return 'danger' // 已取消
    default:
      return 'info'
  }
}

//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.signing_start_date = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.signing_end_date = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.signing_start_date = null
    form.value.signing_end_date = null
  }
}

//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

//点击跳转
const handleJump = (type: string, row?: Record<string, any>) => {
  push({
    path: `/orderReturn-management/orderReturn/${type}`,
    query: { [(row && 'id') as string]: row?.id }
  })
}

//点击取消
const handleCancel = (type: string, row: Record<string, any>) => {
  ElMessageBox.confirm(t('orderReturn.confirmCancel'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      if (type === 'single') {
        // 单个取消使用新接口
        await cancelSingleDataApi(row.id)
      } else {
        // 批量取消使用原接口
        await cancelDataApi({
          id: multipleSelection.value.map((item: Record<string, any>) => item.id)
        })
      }
      ElMessage.success(t('orderReturn.cancelSuccess'))
      await initialize()
    })
    .catch(() => {})
}

const examineHandle = (row, type) => {
  ElMessageBox.confirm(t('common.message.operate'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let params = {
        status: type
      }
      const resp = await examineDataApi(row.id, params)
      if (resp.code === 0) {
        ElMessage.success(t('common.success'))
        initialize()
      }
    })
    .catch(() => {})
}

//打开选择客户弹框
const handleOpenCustomer = () => {
  nextTick(() => {
    DialogCustomerCheckedRef!.value!.dialogVisible = true
    DialogCustomerCheckedRef!.value!.initialize(
      form.value.user_id ? [{ ...form.value, id: form.value.user_id }] : []
    )
  })
}

//接收勾选中的客户
const getExposeCustomerData = (val: any[]) => {
  if (!val || !val.length) return
  form.value.customer_id = val[0].id
  form.value.customer_name = val[0].cusname
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  modelList.value = resp.data.model
  operatorList.value = resp.data.operator
  reasonList.value = resp.data.return_reason
  returnorderTypeList.value = resp.data.returnorder_type
  orderTypeList.value = resp.data.order_type
  statusList.value = resp.data.status
}

//根据接口枚举匹配出中文名称
const useEnumeratePicker = (
  enumList: any[],
  field: string | number,
  key?: string,
  value?: string
) => {
  if (!enumList) return
  const matchItem =
    enumList.find((item: Record<string, any>) => item[value ?? 'value'] === field) || {}
  return matchItem[key ?? 'label'] || ''
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = () => {
  form.value = {
    returnorder_no: '',
    customer_name: '',
    owner: '',
    date: '',
    min_total_amount: undefined,
    max_total_amount: undefined,
    min_paid_amount: undefined,
    max_paid_amount: undefined,
    return_reason: '',
    signing_start_date: '',
    signing_end_date: '',
    pageIndex: 1,
    pageSize: 20
  }
  paginationTotal.value = 0
  initialize()
}

onMounted(() => {
  getDropDownBoxInfo()
  initialize()
})

const tableColumns = useOrderReturnTableColumns(
  handleJump,
  examineHandle,
  handleCancel,
  useEnumeratePicker,
  returnorderTypeList,
  orderTypeList,
  operatorList,
  statusList
)
</script>

<style lang="less" scoped>
// 覆盖全局移动端样式
@media (width <= 768px) {
  .mobile-form .el-button {
    display: flex !important;
    margin-bottom: 0 !important;
    justify-content: center !important;
  }
}

:deep(.el-table--default .el-table__cell) {
  padding: 2px 0 !important;
}

:deep(.el-table--default .cell) {
  padding: 0 4px;
}

// 修复移动端搜索栏样式，实现左右对齐不换行
.mobile-form {
  @media (width <= 768px) {
    .el-form-item {
      display: flex !important;
      align-items: center !important;
      width: 100% !important;
      margin-bottom: 16px !important;

      .el-form-item__label {
        display: inline-block !important;
        width: 80px !important;
        max-width: none !important;
        min-width: 80px !important;
        margin-bottom: 0 !important;
        overflow: visible !important;
        text-align: left !important;
        text-overflow: unset !important;
        white-space: normal !important;
        flex-shrink: 0 !important;
      }

      .el-form-item__content {
        display: flex !important;
        width: calc(100% - 80px) !important;
        margin-left: 12px !important;
        flex: 1 !important;
        flex-wrap: nowrap !important;
        align-items: center !important;

        .el-input,
        .el-select,
        .el-date-picker {
          width: 100% !important;
        }

        .el-input-number {
          width: 102px !important;
          flex-shrink: 0 !important;
        }

        // 数字输入框组保持在同一行
        .el-input-number + .el-input-number {
          margin-left: 8px !important;
        }

        // 确保~符号不换行
        .el-input-number + span + .el-input-number {
          margin-left: 8px !important;
        }
      }
    }
  }
}

// 强制修复数字输入框换行问题
:deep(.mobile-form) {
  @media (width <= 768px) {
    .el-form-item__content {
      display: flex !important;
      flex-wrap: nowrap !important;
      align-items: center !important;

      .el-input-number {
        flex-shrink: 0 !important;
        min-width: 80px !important;
      }
    }
  }
}
</style>
